﻿using AutoMapper.Internal.Mappers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Himp.Platform
{
    /// <summary>
    /// 
    /// </summary>
    public class DataTableDictService : CrudAppService<DataTableDict, DataTableDictDto, Guid, DataTableDictInput, DataTableDictCreateDto, DataTableDictUpdateDto>
    {
        private IRepository<DataTableDict, Guid> _stConfigRepository;

        public DataTableDictService(IRepository<DataTableDict, Guid> StConfigRepository) : base(StConfigRepository)
        {
            _stConfigRepository = StConfigRepository;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public override async Task<PagedResultDto<DataTableDictDto>> GetListAsync(DataTableDictInput input)
        {
            var iQuery = await _stConfigRepository.GetQueryableAsync();
            iQuery = iQuery.WhereIf(!string.IsNullOrEmpty(input.Filter), i => i.DataTableName.Contains(input.Filter));

            if (input.Pi == 0)
            {
                var itemsDto = ObjectMapper.Map<List<DataTableDict>, List<DataTableDictDto>>(iQuery.ToList());

                return new PagedResultDto<DataTableDictDto>(itemsDto.Count, itemsDto);
            }
            else
            {
                var totalCount = iQuery.Count();
                var items = iQuery.Page(input.Pi, input.Ps);
                var itemsDto = ObjectMapper.Map<List<DataTableDict>, List<DataTableDictDto>>(items.ToList());

                return new PagedResultDto<DataTableDictDto>(totalCount, itemsDto);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public override async Task<DataTableDictDto> CreateAsync(DataTableDictCreateDto input)
        {
            var stdTableDict = ObjectMapper.Map<DataTableDictCreateDto, DataTableDict>(input);
            stdTableDict.SetStdTableCodg(Guid.NewGuid().ToString());
            stdTableDict = await _stConfigRepository.InsertAsync(stdTableDict);

            return ObjectMapper.Map<DataTableDict, DataTableDictDto>(stdTableDict);
        }
    }
}
